import {Component, EventEmitter, OnInit, Output} from '@angular/core';
import {UserDetails} from '../UserDetails';
import {userDetails, UserService} from '../service/user.service';

@Component({
  selector: 'app-details',
  templateUrl: './user-details.component.html',
  styleUrls: ['./user-details.component.css'],
  providers: [UserService]
})
export class UserDetailsComponent implements OnInit {

  userInfo: UserDetails = new UserDetails();
  username: string;
  @Output()
  emitValue: EventEmitter<string> = new EventEmitter<string>();
  rawPassword: string;
  newPassword: string;
  newPassword2: string;

  constructor(private userService: UserService) {
    this.userInfo.nickname = userDetails['nickname'];
    this.userInfo.username = userDetails['username'];
    this.userInfo.email = userDetails['email'];
    this.userInfo.gender = userDetails['gender'];
    this.userInfo.head = userDetails['head'];
    this.userInfo.lastLoginTime = userDetails['lastLoginTime'];
    this.userInfo.phone = userDetails['phone'];
    this.userInfo.birthday = userDetails['birthday'];
    this.userInfo.location = userDetails['location'];
    this.userInfo.id = userDetails['id'];
  }

  ngOnInit() {
  }

  changePwd() {
    if (this.newPassword === this.newPassword2) {
      this.userService.changePassword(this.rawPassword, this.newPassword);
    } else {
      alert('两次输入的密码不一致');
    }
  }

  saveUserInfo() {
    if (this.userInfo.phone !== undefined && this.userInfo.phone.length > 0) {
      const phoneReg = /^[1][3,4,5,7,8][0-9]{9}$/;
      if (!phoneReg.test(this.userInfo.phone)) {
        alert('错误的手机号码');
        return;
      }
    }
    const emailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
    if (this.userInfo.email !== undefined && this.userInfo.email.length > 0) {
      if (!emailReg.test(this.userInfo.email)) {
        alert('邮箱格式不正确');
        return;
      }
    }
    this.userService.save(this.userInfo, function (result) {
      alert('修改成功');
    });
  }
}
